<template>
    <div class="register_box">
        <div class="welcome">欢迎注册青木川的个人博客</div>
        <div class="avatar">
            <input
                type="file"
                accept="image/*"
                @change="upload_avatar_change"
                id="upload_avatar" />
            <img
                :src="avatar"
                @click="upload_avatar_click" />
        </div>
        <el-tooltip
            :content="options.account_options.content"
            :placement="options.account_options.placement"
            :auto-close="options.account_options.close"
            :effect="options.account_options.effect">
            <el-input
                v-model="register_data.account"
                autocomplete="new-password"
                placeholder="账号"
                :spellcheck="false"
                @change="account_input_change" />
        </el-tooltip>
        <el-tooltip
            :content="options.password_options.content"
            :placement="options.password_options.placement"
            :auto-close="options.password_options.close"
            :effect="options.password_options.effect">
            <el-input
                v-model="register_data.password"
                autocomplete="new-password"
                name="register_pwd"
                type="password"
                placeholder="密码"
                show-password
                :spellcheck="false"
                @change="password_input_change" />
        </el-tooltip>
        <el-tooltip
            :content="options.mail_options.content"
            :placement="options.mail_options.placement"
            :auto-close="options.mail_options.close"
            :effect="options.mail_options.effect">
            <el-input
                v-model="register_data.mail"
                placeholder="邮箱"
                type="email"
                :spellcheck="false"
                @change="mail_input_change">
                <template #append>
                    <el-button
                        :disabled="!SEND_CODE_is_click"
                        @click="send_code_click"
                        >{{ SEND_CODE_content }}</el-button
                    >
                </template>
            </el-input>
        </el-tooltip>
        <el-tooltip
            :content="options.code_options.content"
            :placement="options.code_options.placement"
            :auto-close="options.code_options.close"
            :effect="options.code_options.effect">
            <el-input
                v-model="register_data.code"
                placeholder="验证码"
                :spellcheck="false"
                @change="code_input_change" />
        </el-tooltip>
        <div class="register">
            <el-button @click="register_click">注册</el-button>
        </div>
        <div class="bottom_navigation">
            <span @click="return_click">已有账号?返回登录!</span>
        </div>
    </div>
</template>

<script setup>
import { el_message } from '@/utils/el_message';
import { reactive, ref, onBeforeMount, onMounted } from 'vue';
import { useIndexStore } from '@/store/model/index';
import { send_code, proving_code, register } from '@/axios/home/index';
import { useRouter } from 'vue-router';
import { send_msg, listen_msg } from '@/utils/tag_msg.js';

const store = useIndexStore();
const router = useRouter();

const register_data = reactive({
    account: '',
    password: '',
    mail: '',
    code: '',
});

const flag = reactive({
    account_flag: false,
    password_flag: false,
    mail_flag: false,
    code_flag: false,
});

const options = reactive({
    account_options: {
        content: '请输入4至16位的汉字,大小写字母或数字来作为您的账号。', // tooltip的显示内容
        close: 2000, // 出现多少毫秒后隐藏
        placement: 'left', //出现位置
        effect: 'customized', //使用什么样式  dark：黑  light：白  customized：定制
    },
    password_options: {
        content: '请输入6至16位的大小写字母或数字来作为您的账号密码。', // tooltip的显示内容
        close: 2000, // 出现多少毫秒后隐藏
        placement: 'left', //出现位置
        effect: 'customized', //使用什么样式  dark：黑  light：白  customized：定制
    },
    mail_options: {
        content: '请输入您的邮箱号。', // tooltip的显示内容
        close: 2000, // 出现多少毫秒后隐藏
        placement: 'left', //出现位置
        effect: 'customized', //使用什么样式  dark：黑  light：白  customized：定制
    },
    code_options: {
        content: '请输入您的验证码。', // tooltip的显示内容
        close: 2000, // 出现多少毫秒后隐藏
        placement: 'left', //出现位置
        effect: 'customized', //使用什么样式  dark：黑  light：白  customized：定制
    },
});

const SEND_CODE_content = ref('发送验证码');
const SEND_CODE_is_click = ref(true);
let SEND_CODE_timer = null;
const avatar = ref(`${store.web_url.webPath}/img/default/mrtx.webp`);
const file_val = ref(null);
const cropper_window = ref(null);

onMounted(() => {
    listen_msg((data) => {
        if (data.type === 'load_success') {
            send_msg({
                msg:{...file_val.value},
                type:"send_file"
            });
        }else if(data.type === 'get_img_url'){
            avatar.value = data.msg
        }
    });
});

onBeforeMount(() => {
    // 当进入组件时先判断是否有start状态以及start状态是否在60秒内
    if (store.start) {
        // this.countdown = parseInt(storedCountdown, 10);
        const current_time = Date.parse(new Date());
        const diff_time = (current_time - store.start) / 1000;
        if (diff_time >= 60) {
            // 如果时间差大于60s，则代表上次倒计时已经结束
            // 那么就将pinia中的数据恢复初始状态
            store.update_countdown(null);
            store.update_start(null);
        } else if (diff_time >= 0 && diff_time < 60) {
            // 如果时间差小于60s，则代表上次的倒计时并未结束
            // 那么就将pinia中的数据更新为当前状态
            let initial_time = 60 - diff_time;
            store.update_countdown(initial_time);
            // 设置是否可以点击
            SEND_CODE_is_click.value = false;
            // 然后开始倒计时
            let interval_callback = () => {
                initial_time = initial_time--;
                store.update_countdown(initial_time);
                SEND_CODE_content.value = `${initial_time--}s后再次获取`;
                // 当倒计时为0时，删除定时器,恢复按钮的content，是否点击，以及是否进入倒计时状态
                if (store.count_down === 0) {
                    SEND_CODE_content.value = '发送验证码';
                    SEND_CODE_is_click.value = true;
                    store.update_countdown(null);
                    clearInterval(SEND_CODE_timer);
                }
            };
            interval_callback();
            SEND_CODE_timer = setInterval(interval_callback, 1000);
        }
    }
});

// input框change事件
const upload_avatar_change = (e) => {
    const file = e.target.files[0];
    const URL = window.URL || window.webkitURL;
    file_val.value = {
        name: file.name,
        value: URL.createObjectURL(file),
    };
    e.target.value = null;
    const reader = new FileReader();
    reader.onload = function () {
        const { href } = router.resolve('/cropping');
        const route = window.location.origin + href;
        const width = 1000;
        const height = 800;
        const screenWidth = window.screen.width;
        const screenHeight = window.screen.height;
        const left = (screenWidth - width) / 2;
        const top = (screenHeight - height) / 2;
        const options = [
            `width=${width}px`,
            `height=${height}px`,
            `left=${left}`,
            `top=${top}`,
            'toolbar=no',
            'menubar=no',
            'scrollbars=no',
            'resizable=no',
            'location=no',
            'status=no',
            'centerscreen=yes',
        ].join();
        cropper_window.value = window.open('', '_blank', options);
        cropper_window.value.location.href = route;
        cropper_window.value.onload = () => {
            cropper_window.value.document.title = '上传头像';
        };
    };
    reader.readAsDataURL(file);
};

// 触发img标签的点击事件
const upload_avatar_click = () => {
    document.getElementById('upload_avatar')?.click();
};

const account_input_change = () => {
    const regex = /^[A-Za-z0-9\u4e00-\u9fa5]{4,16}$/;
    if (regex.test(register_data.account)) {
        flag.account_flag = true;
    } else {
        flag.account_flag = false;
        el_message(
            '请输入4至16位的汉字,大小写字母或数字,来作为您的账号!',
            'warning'
        );
    }
};

const password_input_change = () => {
    const regex = /^[A-Za-z0-9]{6,16}$/;
    if (regex.test(register_data.password)) {
        flag.password_flag = true;
    } else {
        flag.password_flag = false;
        el_message(
            '请输入6至16位大小写字母或数字,来作为您账号的密码!',
            'warning'
        );
    }
};

const mail_input_change = () => {
    const regex = /^[\w.-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    if (regex.test(register_data.mail)) {
        flag.mail_flag = true;
    } else {
        flag.mail_flag = false;
        el_message('邮件格式错误!', 'warning');
    }
};

const code_input_change = () => {
    const regex = /^[0-9]{6}$/;
    if (regex.test(register_data.code)) {
        flag.code_flag = true;
    } else {
        flag.code_flag = false;
        el_message('请输入6位数的验证码!', 'warning');
    }
};

const send_code_click = async () => {
    if (flag.mail_flag) {
        // 如果点击按钮时countdown为null则代表当前并未进入倒计时状态
        // 那么就要给start赋值为当前点击的时间
        store.update_start(Date.parse(new Date()));
        // 并给countdown赋值为基础值
        let initial_time = 60;
        store.update_countdown(initial_time);
        // 设置是否可以点击
        SEND_CODE_is_click.value = false;
        // 然后开始倒计时
        let interval_callback = () => {
            initial_time = initial_time--;
            store.update_countdown(initial_time);
            SEND_CODE_content.value = `${initial_time--}s后再次获取`;
            // 当倒计时为0时，删除定时器,恢复按钮的content，是否点击，以及是否进入倒计时状态
            if (store.count_down === 0) {
                SEND_CODE_content.value = '发送验证码';
                SEND_CODE_is_click.value = true;
                store.update_countdown(null);
                clearInterval(SEND_CODE_timer);
            }
        };
        interval_callback();
        SEND_CODE_timer = setInterval(interval_callback, 1000);
        let write_res = await send_code({
            mail: register_data.mail,
            start_time: new Date().getTime(),
        });
    } else {
        el_message('请输正确格式的邮箱!', 'warning');
    }
};

const register_click = async () => {
    if (
        flag.account_flag &&
        flag.password_flag &&
        flag.mail_flag &&
        flag.code_flag
    ) {
        // 所有正则都正确就执行注册
        let proving_res = await proving_code({
            mail: register_data.mail,
            code: register_data.code,
            current_time: new Date().getTime(),
        });
        if (proving_res.code === 200) {
            let register_res = await register({
                user_name: register_data.account,
                user_pwd: register_data.password,
                user_img: avatar.value,
                is_administrators: false,
                mail: register_data.mail,
            });
            if (register_res.code === 200) {
                router.push(`/admin/login`);
            }
        }
    } else {
        // 当某个正则验证不通过时就分开判断那个正则不正确并给出提示
        let flag_data_list = [
            [flag.account_flag, '账号'],
            [flag.password_flag, '密码'],
            [flag.mail_flag, '邮箱号'],
            [flag.code_flag, '验证码'],
        ];
        let flag_str_list = flag_data_list
            .filter((v) => {
                return !v[0];
            })
            .map((v) => {
                return v[1];
            });
        el_message(`请检查${flag_str_list.join('&')},格式是否正确!`, 'warning');
    }
};

const return_click = () => {
    router.push(`/admin/login`);
};
</script>

<style scoped lang="less">
.register_box {
    width: 320px;
    font-size: 0px;
    box-sizing: border-box;
    border-radius: 12px;
    border: 2px solid @tml;
    background-color: rgba(244, 244, 244, 0.3);
    padding: 10px;

    .welcome {
        font-size: 24px;
        font-weight: 900;
        margin-bottom: 10px;
    }

    .avatar {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        cursor: pointer;
        margin: auto;
        #upload_avatar {
            display: none;
        }
        img {
            width: 100px;
            height: 100px;
            border-radius: 50%;
        }
    }

    :deep(.el-input) {
        margin: 10px 0;

        .el-input__wrapper {
            background-color: @tmb;
            box-shadow: 0 0 0 0;
        }

        .el-input-group__append {
            background-color: @tmb;
            .el-button {
                width: 1.2rem;
                height: 100%;
                font-size: 0.14rem;
            }
        }
    }

    .register {
        width: 100%;
        display: flex;
        justify-content: center;
        margin-top: 10px;
    }

    .bottom_navigation {
        width: 100%;
        margin-top: 10px;
        font-size: 14px;
        font-weight: 900;
        color: @hs;
        display: flex;
        justify-content: flex-end;
        span {
            cursor: pointer;
        }
    }
}
</style>
